//
//  VeganIsEasyAppDelegate.m
//  VeganIsEasy
//
//  Created by Matthew Feinberg on 5/14/09.
//  Copyright __MyCompanyName__ 2009. All rights reserved.
//

#import "VeganIsEasyAppDelegate.h"
#import "BoozeTableViewController.h"
#import "CreditsViewController.h"

// Private interface for AppDelegate - internal only methods.
@interface VeganIsEasyAppDelegate (Private)
- (void)createEditableCopyOfDatabaseIfNeeded;
- (void)initializeDatabase;
@end

@implementation VeganIsEasyAppDelegate

// Creates a writable copy of the bundled default database in the application Documents directory.
- (void)createEditableCopyOfDatabaseIfNeeded {
    // First, test for existence.
    BOOL success;
	NSString *databaseFn = @"veganiseasy_1.1.sqlite";
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:databaseFn];

    success = [fileManager fileExistsAtPath:writableDBPath];
	
	// During development, install a new version every time
	//if (success) {
	//	[fileManager removeItemAtPath:writableDBPath error:&error];
	//	success = NO;
	//}	
	
    if (success) return;
    // The writable database does not exist, so copy the default to the appropriate location.
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseFn];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
    if (!success) {
        NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }
}

// Open the database connection and retrieve minimal information for all objects.
- (void)initializeDatabase {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"veganiseasy.sqlite"];
    // Open the database. The database was prepared outside the application.
    if (sqlite3_open([path UTF8String], &database) != SQLITE_OK) {
        // Even though the open failed, call close to properly clean up resources.
        sqlite3_close(database);
        NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
        // Additional error handling, as appropriate...
    }
}

- (void)applicationDidFinishLaunching:(UIApplication *)application {
	// Create the main application window
	window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
	
	// Prepare the database connection
	[self createEditableCopyOfDatabaseIfNeeded];
	[self initializeDatabase];
	
	NSMutableArray *controllers = [[NSMutableArray alloc] init];
	
	// A navigation controller will be used to navigate the different views, so create it now
	UIViewController *rootViewController = (UIViewController *)[[BoozeTableViewController alloc] initWithDatabase:database];
	UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:rootViewController];
	[rootViewController release];
	[controllers addObject:nav];
	[nav release];
	
	CreditsViewController *credits = [[CreditsViewController alloc] init];
	[controllers addObject:credits];
	[credits release];
	
	// Create the tab bar controller which contains all other parts of the app
	tbarController =[[UITabBarController alloc] init];
	[tbarController retain];
	
	// Add the controllers to the tab bar
	[tbarController setViewControllers:controllers];
	[tbarController setCustomizableViewControllers:controllers];	
	[controllers release];
	
	tbarController.delegate = self;
	
	// Add the navigation controller's view to the window
//	[window addSubview:nav.view];
	[window addSubview:tbarController.view];
//	[tbarController release];
	
	// Make the window we created the key window on the phone and make it visible.
	// This will make the navigation controller's view visible and in turn the root view controller
	[window makeKeyAndVisible];
	//[window autorelease];
}

- (void)dealloc {
	// Release resources used by sqlite
	sqlite3_close(database);
	[tbarController release];
	[window release];
    [super dealloc];
}

@end
